<?php

namespace Common\Utils;
header('Content-type: text/html; charset=utf-8');
header('Access-Control-Allow-Origin:*');//允许跨域

class YouaErp
{
    public function return_data($data, $key_value, $url)
    {
        $sign = $this->makeSign($data, $key_value);
        # echo "sign=".$sign."<br>";
        $data['sign'] = $sign;
        $str = json_encode($data);
        $result = $this->curl_form($str, $url, 'http://218.76.51.168:8088/V0/GetDept.ashx');
        return $result;
    }

    /**
     * 生成签名验签
     * @param array $requestData
     * @return string
     */
    public function makeSign(array $requestData, $key_value)
    {
        $md5String = '';
        $newKey = array();
        foreach ($requestData as $key => $value) {
            $k = lcfirst($key);
            $newKey[$k] = $key;
        }
        ksort($newKey);
        foreach ($newKey as $key => $value) {
            $v = is_array($requestData[$value]) ? json_encode($requestData[$value]) : $requestData[$value];
            $md5String .= $value . "=" . $v . "&";
        }
        $md5String = rtrim($md5String, "&");
        $signString = $md5String . $key_value;
        //$signString = base64_encode( $signString );
        //echo "<br>===".$signString;
        return md5($signString);
    }

    /**
     * 生成签名验签
     * @param array $post_data
     * @return json
     */

    public function curl_form($post_data, $sumbit_url, $http_url)
    {

        //初始化
        $ch = curl_init();
        //设置变量
        curl_setopt($ch, CURLOPT_URL, $sumbit_url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//执行结果是否被返回，0是返回，1是不返回
        curl_setopt($ch, CURLOPT_HEADER, 0);//参数设置，是否显示头部信息，1为显示，0为不显示
        curl_setopt($ch, CURLOPT_REFERER, $http_url);
        //表单数据，是正规的表单设置值为非0
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);//设置curl执行超时时间最大是多少
        //使用数组提供post数据时，CURL组件大概是为了兼容@filename这种上传文件的写法，
        //默认把content_type设为了multipart/form-data。虽然对于大多数web服务器并
        //没有影响，但是还是有少部分服务器不兼容。本文得出的结论是，在没有需要上传文件的
        //情况下，尽量对post提交的数据进行http_build_query，然后发送出去，能实现更好的兼容性，更小的请求数据包。
        curl_setopt($ch, CURLOPT_POSTFIELDS, array("request" => $post_data));
        //执行并获取结果
        $output = curl_exec($ch);
        if ($output === FALSE) {
            var_dump("cUrl Error:" . curl_error($ch));
        }
        //    释放cURL句柄
        curl_close($ch);
        return $output;
    }

    // 资料事务处理。
    public function trans($arr_data, $Model = "")
    {
        // echo 111;
        try {
            if (empty($Model)) {
                $Model = M();
            }
            $Model->startTrans();
            foreach ($arr_data as $key => $value) {
                $Model->execute($value);
            }
        } catch (\Exception $e) {
            $msg = "资料转档失败,error sql=" . $Model->getLastSql();
            $Model->rollback();
            error_log(date("Y-m-d H:i:s"). $msg . "\r\n", 3, C('LOG_PATH') . date('y_m_d') . '_trans.log');
            echo $e->getMessage() . '事物回滚';
            return false;
        }
        $Model->commit();
        error_log(date("Y-m-d H:i:s") . "资料转档成功！" . "\r\n", 3, C('LOG_PATH') . date('y_m_d') . '_trans.log');
        return true;
    }

    public function return_sql($arr_data, $mysql_table_name, $Model = "")
    {
        if (empty($Model)) {
            $Model = M();
        }
        $arr_sql = array();
        $table_key = '';
        foreach ($arr_data as $key => $value) {
         /*  foreach ($arr_data[$key] as $key2 => $val2) {
               if(count($arr_data[$key])==1)  // 只有一个元素
               $table_key = $key2;
            }*/
            if ($mysql_table_name == "ymall_erp_group") {
                $namelist = explode("|", $value['SellerPathStr']);
                $num = count($namelist);
                for ($i = 0; $i < $num; $i++) {
                    //用拼接的sql吧。
                    $name = $namelist[$i];
                    $depart_no = substr($value['SellerPath'], 0, pow(2, $i + 1));
                    if ($Model->table("ymall_erp_group")->where("group_path='$depart_no'")->count())
                        $arr_sql[] = "update ymall_erp_group set name='$name',update_by='sys',update_time=now() where group_path='$depart_no'";
                    else
                        $arr_sql[] = "insert into ymall_erp_group(group_path,name, create_by, update_by,create_time,update_time) values('$depart_no','$name','sys','sys',now(),now())";
                }

             } elseif ($mysql_table_name == "sys_user") {
                $employee_no = $value['Rydm'];//员工号
                $depart_no = $value['SellerPath'];//部门代号
                $name = $value['Name'];
                $g_id = $Model->table("ymall_erp_group")->where("group_path='$depart_no'")->getField('id');
                if ($g_id) {
                    //做sql处理,通过员工号去做对应的资料处理
                    if ($Model->table("sys_user")->where("login_name='$employee_no'")->count())
                        $arr_sql[] = "update sys_user set group_id='$g_id',update_by='sys',update_time=now(),user_name='$name' where login_name='$employee_no'";
                    else
                        $arr_sql[] = "Insert into sys_user(group_id,login_name, user_name ,user_type,create_by,create_time)values('$g_id','$employee_no','$name','01','sys',now())";

                }
                //往sys_user_data_group
                if (strlen($depart_no) == 8) {
                    $g_id2 = $Model->table("sys_user_data_group")->where("group_path='$depart_no' and user_id='$employee_no'")->field('id')->select();
                    #echo $Model->getLastSql()."<br>g_id2=";
                    if (!$g_id2) {
                        $arr_sql[] = "Insert into sys_user_data_group(user_id,group_path)VALUES ('$employee_no','$depart_no')";
                    }
                    /* else
                    $arr_sql[] = "update sys_user_data_group set user_id='$employee_no' where group_path='$depart_no'";*/

                }
                //往sys_user_role塞资料，默认门店员2,如果有员工号不做处理
                if (!$Model->table("sys_user_role")->where("user_id='$employee_no'")->count()) {
                    $arr_sql[] = "Insert into sys_user_role(user_id,role_id)VALUES ('$employee_no','2')";
                }


            } elseif ($mysql_table_name == "ymall_category") {
                $namelist = explode("|", $value['CategoryPathstr']);
                $num = count($namelist);
                for ($i = 0; $i < $num; $i++) {
                    //用拼接的sql吧。
                    $name = $namelist[$i];
                    $Category_no = substr($value['CategoryPath'], 0, ($i + 1) * 2);
                    if ($Model->table("ymall_category")->where("category_path='$Category_no'")->count())
                        $arr_sql[] = "update ymall_category set name='$name',update_by='sys',update_time=now() where category_path='$Category_no'";
                    else
                        $arr_sql[] = "insert into ymall_category(category_path,name ,create_by,create_time)values('$Category_no','$name', 'sys',now())";
                }
            } elseif ($mysql_table_name == "ymall_item") {
                $erp_item_code = $value['itemCode']; //商品码
                $name = $value['name'];  //名称
                $brand_id = $value['brandId'];   //品牌代号
                $categoryPath = $value['categoryPath']; //分类代号
                $categoryPath_id = $Model->table("ymall_category")->where("category_path='$categoryPath'")->getField('id');
                $mysql_brandid = $Model->table("ymall_brand")->where("erp_brand_code='$brand_id'")->getField('id');
                $str = "";
                if ($mysql_brandid) $str = "brand_id='$mysql_brandid',";
                $str2 = "";
                if($categoryPath_id) $str2 = "category_id='$categoryPath_id',";
                $arr_sql[] = "update ymall_item set name='$name'," . $str . " category_path='$categoryPath',".$str2." update_by='sys',update_time=now() where erp_item_code='$erp_item_code'";
                $arr_sku_data = $value['sku'];
                foreach ($arr_sku_data as $key2 => $val) {
                    $sku_code = $val['skuCode']; //sku商品码
                    $price = $val['lsdj'];//售价
                    $sale_props_str = $val['sale_props_str']; //销售规格
                    $barcode = $val['barcode'];//barcode编码
                    $arr_sql[] = "update ymall_item_sku set sales_price='$price',sale_props_str='$sale_props_str',barcode='$barcode',update_by='sys',update_time=now() where erp_sku_code='$sku_code'";

                }

            } elseif ($mysql_table_name == "ymall_brand") {
                $erp_brand_code = $value['branndId']; //商品码
                $name = $value['name'];  //名称
                $ename = $value['eName'];   //英文名
                if ($Model->table("ymall_brand")->where("erp_brand_code='$erp_brand_code'")->count())
                    $arr_sql[] = "update ymall_brand set name='$name',eng_name='$ename',update_by='sys',update_time=now() where erp_brand_code='$erp_brand_code'";
                else
                    $arr_sql[] = "insert into ymall_brand(erp_brand_code,name,eng_name,create_by,create_time) VALUES ('$erp_brand_code','$name','$ename','sys',now() )";

            }
        }
        return array_unique($arr_sql);

    }
    public function Update_Temp_Data($arr_data,$table_name){
        $arr_sql = array();
        $table_key = '';

        foreach ($arr_data as $key => $val) {
            foreach ($arr_data[$key] as $key2 => $val2) {
                $table_key = $key2;
            }
            $arr_sql[] = "update temp_data set is_transfer='Y',update_date=now() where table_name='$table_name' and `key`='$table_key' and `value`='$val[$table_key]' ";

        }
        return $arr_sql;
    }

    public function temp_sql($arr_data, $table_name)
    {
        if (empty($Model)) {
            $Model = M();
        }
        $table_key = '';
        $arr_sql = array();
        foreach ($arr_data as $key => $val) {
            foreach ($arr_data[$key] as $key2 => $val2) {
                $table_key = $key2;
            }
            if ($table_name == 'ymall_erp_group') {
                if ($table_key <> "sellerPath") {
                    $this->toJson('参数异常!', '', -1);
                }
            } elseif ($table_name == 'sys_user') {
                if ($table_key <> "rydm") {
                    $this->toJson('参数异常!', '', -1);
                }
            } elseif ($table_name == 'ymall_category') {
                if ($table_key <> "categoryPath") {
                    $this->toJson('参数异常!', '', -1);
                }
            } elseif ($table_name == 'ymall_item') {
                if ($table_key <> "sku" and $table_key <> "barcode" and $table_key <> "sellerPath") {
                    $this->toJson('参数异常!', '', -1);
                }
                $table_key = "sku|barcode|sellerPath";
                $value = $val['sku'] . "|" . $val['barcode'] . "|" . $val['sellerPath'];

            } elseif ($table_name == 'ymall_brand') {
                if ($table_key <> "branndId") {
                    $this->toJson('参数异常!', '', -1);
                }
            } elseif ($table_name == 'ymall_stock') { //sku|sellerPath
                if ($table_key <> "sku" and $table_key <> "sellerPath") {
                    $this->toJson('参数异常!', '', -1);
                }
                $table_key = "sku|sellerPath";
                $value = $val['sku'] . "|" . $val['sellerPath'];
            }
            if (strpos("ymall_item|ymall_stock", $table_name) === false)
                $value = $val[$table_key];
            $arr_sql[] = "insert into temp_data(table_name,`key`,`value`,create_date)values (
                         '$table_name','$table_key','$value',now())";
        }
        return array_unique($arr_sql);

    }

    /**
     * 重写AJAX返回
     */
    public function toAjax($data)
    {
        header("Content-type:application/json;charset=utf-8");
        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 重写的AJAX方法
     */
    public function toJson($message, $result = array(), $code = 0)
    {
        $return['returnCode'] = $code;
        $return['info'] = $message;
        $return['data'] = $result;
        $this->toAjax($return);
    }

    /**
     * 数组筛选生成新的二维数组
     * @param  $arr 二维数组
     * @param  $table_name
     */
    public function new_arr($arr, $table_name)
    {

        $data = array();
        foreach ((array)$arr as $k => $val) {
            if ($table_name == $val['table_name']) {
                $data[][$val['key']] = $val['value'];
            }
        }
        return $data;

    }
}